// 引入vue和vuex
import Vue from 'vue'
import Vuex from 'vuex'
// 引入axios
import axios from 'axios'
// 使用插件
Vue.use(Vuex)

// 准备actions——用于响应组件中的动作
const actions = {
    // 想服务器发送请求，拿到所有博客的信息
    async getAllBlog({ commit }) {
        let res = await axios.get('http://1.12.58.122:3007/api/article/all')
        if (res.data.status==0) {
            commit('GETALLBLOG', res.data.data)
        }
    },
    async searchSort({commit},b){
        let sort = b
        let res = await axios.post('http://1.12.58.122:3007/api/article/sortSearch' , {sort:sort})
        if(res.data.status == 0){
            commit('SEARCHSORT',res.data.data)
        }
    },
    async searchKW({commit},k){
        let keyWord = k
        let res = await axios.post('http://1.12.58.122:3007/api/article/keySearch',{keyWord})
        if(res.data.status == 0){
            commit('SEARCHKW',res.data.data)
        }
    },
    async getAllImg({commit}){
        let res = await axios.get('http://1.12.58.122:3007/api/geturl')
        if(res.data.status == 0){
            commit('GETALLIMG',res.data.data)
        }
    }
}

// 准备mutations——用于操作数据(state)
const mutations = {
    GETALLBLOG(state, blogList) {
        state.blogList = blogList
        const arr1 = []
        for(var i =0;i<blogList.length;i++){
           arr1.push(blogList[i].sort)
           state.sortList = [...new Set(arr1)]
        }
    },
    SEARCHSORT(state,sortSearcgList){
        state.sortSearcgList = sortSearcgList
    },
    SEARCHKW(state,data){
        state.keyWordArticle = data
    },
    GETALLIMG(state,data){
        state.imgUrl = data
    }
}

// 准备state——用于存储数据
const state = {
    // state中数据默认初始值别瞎写，服务器返回对象那就是空对象，服务器返回数组那就是空数组
    blogList: [],
    sortSearcgList:[],
    sortList:[],
    keyWordArticle:[],
    imgUrl:[]
}

const getters = {
}

// 创建并暴露store
const store = new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})

export default store